/**
 * 
 */
package edu.cmu.cs.webapp.ioms.views;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;

import edu.cmu.cs.webapp.ioms.IOMSActivator;
import edu.cmu.cs.webapp.ioms.dao.DataAccessException;
import edu.cmu.cs.webapp.ioms.dao.impl.IngredientDAOImpl;
import edu.cmu.cs.webapp.ioms.dao.impl.ProductDAOImpl;
import edu.cmu.cs.webapp.ioms.models.Ingredient;
import edu.cmu.cs.webapp.ioms.models.OrderStatus;
import edu.cmu.cs.webapp.ioms.models.Product;
import edu.cmu.cs.webapp.ioms.models.PurchaseOrder;
import edu.cmu.cs.webapp.ioms.perspectives.OrderManagementPerspective;
import edu.cmu.cs.webapp.ioms.utils.DateRange;
import edu.cmu.cs.webapp.ioms.utils.IOMSConstants;
import edu.cmu.cs.webapp.ioms.utils.SWTUtils;

/**
 * @author Christian
 * 
 */
public class OrderDetailsView extends ViewPart implements
		ISelectionChangedListener {

	public static final String ID_VIEW = "edu.cmu.cs.webapp.ioms.views.orderdetails";

	private Combo _orderStatusComb;
	private DateTime _orderDataFromTxt;
	private DateTime _orderDataToTxt;

	// shipping filter
	private DateTime _shippingDateFromTxt;
	private DateTime _shippingDateToTxt;

	// customer
	private Text _clientID;
	private Text _clientFName;
	private Text _clientLName;

	private Text _clientEmail;

	private Button _resetBtn;
	private Button _searchBtn;

	// product and ingredient
	private Combo _prod;
	private Combo _ingredient;

	/**
	 * 
	 */
	public OrderDetailsView() {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets
	 * .Composite)
	 */
	@Override
	public void createPartControl(Composite parent) {
		parent.setLayout(new GridLayout(1, false));

		Composite btnComp = SWTUtils.createComposite(parent, 2, SWT.DEFAULT, 1);

		GridData center = new GridData();
		center.horizontalAlignment = GridData.CENTER;
		_searchBtn = SWTUtils.createPushButton(btnComp, "Search");
		_searchBtn.setLayoutData(center);
		_searchBtn.addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				OrdersListView.getOrdersListViewPart(getViewSite())
						.refreshOrdersView(constructSearchCriteria());
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {

			}
		});

		_resetBtn = SWTUtils.createPushButton(btnComp, "Find All");
		_resetBtn.setLayoutData(center);
		_resetBtn.addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				OrdersListView.getOrdersListViewPart(getViewSite())
						.refreshOrdersView(null);
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO Auto-generated method stub
			}
		});

		int separatorStyle = SWT.SEPARATOR | SWT.HORIZONTAL | SWT.SHADOW_OUT;
		Label separator = new Label(parent, separatorStyle);
		separator.setLayoutData(createGridDataWithSpan());

		// Composite container = SWTUtils.createComposite(parent, 1,
		// SWT.DEFAULT,
		// 1);
		// ((GridLayout) container.getLayout()).marginHeight = 0;
		// ((GridLayout) container.getLayout()).marginWidth = 0;

		// order info
		Group orderGroup = SWTUtils.createGroup(parent, "Order Information", 3);

		SWTUtils.createLabel(orderGroup, "Order Status:", 1).setLayoutData(
				createLabelGridData());
		_orderStatusComb = SWTUtils.createCombo(orderGroup, OrderStatus
				.getLiterals(), 2);
		_orderStatusComb.setLayoutData(createControlGridData());

		// SWTUtils.createLabel(orderGroup, "Order Number:", 1).setLayoutData(
		// createLabelGridData());
		// _orderNumTxt = SWTUtils.createTextBox(orderGroup);
		// _orderNumTxt.setLayoutData(createControlGridData());

		SWTUtils.createLabel(orderGroup, "Order Date From:", 1).setLayoutData(
				createLabelGridData());
		_orderDataFromTxt = new DateTime(orderGroup, SWT.DROP_DOWN);
		_orderDataFromTxt.setLayoutData(createControlGridData());

		SWTUtils.createLabel(orderGroup, "Order Date To:", 1).setLayoutData(
				createLabelGridData());
		_orderDataToTxt = new DateTime(orderGroup, SWT.DROP_DOWN);
		_orderDataToTxt.setLayoutData(createControlGridData());

		// shipping info

		Group shippinGroup = SWTUtils.createGroup(parent,
				"Shipping Information", 3);

		SWTUtils.createLabel(shippinGroup, "Shipping Date From:", 1)
				.setLayoutData(createLabelGridData());
		_shippingDateFromTxt = new DateTime(shippinGroup, SWT.DROP_DOWN);
		_shippingDateFromTxt.setLayoutData(createControlGridData());

		SWTUtils.createLabel(shippinGroup, "Shipping Date To:", 1)
				.setLayoutData(createLabelGridData());
		_shippingDateToTxt = new DateTime(shippinGroup, SWT.DROP_DOWN);
		_shippingDateToTxt.setLayoutData(createControlGridData());

		// client info
		Group clientGroup = SWTUtils.createGroup(parent, "Client Information",
				3);

		SWTUtils.createLabel(clientGroup, "First Name:", 1).setLayoutData(
				createLabelGridData());
		_clientFName = SWTUtils.createTextBox(clientGroup, 2);
		_clientFName.setLayoutData(createControlGridData());

		SWTUtils.createLabel(clientGroup, "Last Name:", 1).setLayoutData(
				createLabelGridData());
		_clientLName = SWTUtils.createTextBox(clientGroup, 2);
		_clientLName.setLayoutData(createControlGridData());

		// SWTUtils.createLabel(clientGroup, "Client Email:", 1).setLayoutData(
		// createLabelGridData());
		// _clientEmail = SWTUtils.createTextBox(clientGroup, 2);
		// _clientEmail.setLayoutData(createControlGridData());

		// Ingredient info
		Group ingGroup = SWTUtils
				.createGroup(parent, "Product & Ingredient", 3);

		SWTUtils.createLabel(ingGroup, "Product:", 1).setLayoutData(
				createLabelGridData());
		_prod = new Combo(ingGroup, SWT.BORDER);
		_prod.setItems(fetchProductList());
		_prod.setLayoutData(createControlGridData());

		SWTUtils.createLabel(ingGroup, "Ingredient:", 1).setLayoutData(
				createLabelGridData());
		_ingredient = new Combo(ingGroup, SWT.BORDER);
		_ingredient.setItems(fetchIngredientList());
		_ingredient.setLayoutData(createControlGridData());

	}

	private String[] fetchProductList() {

		try {
			List<Product> prods = new ProductDAOImpl().getAllProd();
			String[] l = new String[prods.size()];
			for (int i = 0; i < prods.size(); i++) {
				l[i] = prods.get(i).getProd_name();
			}
			return l;

		} catch (DataAccessException e) {

		}

		return new String[0];
	}

	private String[] fetchIngredientList() {
		try {
			List<Ingredient> ings = new IngredientDAOImpl().getAllIngr();
			String[] l = new String[ings.size()];
			for (int i = 0; i < ings.size(); i++) {
				l[i] = ings.get(i).getName();
			}
			return l;

		} catch (DataAccessException e) {

		}

		return new String[0];

	}

	@SuppressWarnings("deprecation")
	protected Map<String, Object> constructSearchCriteria() {
		Map<String, Object> criteria = new HashMap<String, Object>();
		if (this._orderStatusComb.getText() != null
				&& this._orderStatusComb.getText().length() > 0) {
			criteria.put(IOMSConstants.PURCHASE_ORDER__STATUS,
					this._orderStatusComb.getText());
		}

		// constructing order date range
		Date dateFrom = new Date(this._orderDataFromTxt.getYear() - 1900,
				this._orderDataFromTxt.getMonth(), this._orderDataFromTxt
						.getDay());
		Date dateTo = new Date(this._orderDataToTxt.getYear() - 1900,
				this._orderDataToTxt.getMonth(), this._orderDataToTxt.getDay());
		DateRange range = new DateRange(dateFrom, dateTo);
		criteria.put(IOMSConstants.PURCHASE_ORDER__ORDER_DATE, range);

		if (this._clientFName.getText() != null
				&& this._clientFName.getText().trim().length() > 0) {
			criteria.put(IOMSConstants.CLIENT__FNAME, this._clientFName
					.getText().trim());
		}

		if (this._clientLName.getText() != null
				&& this._clientLName.getText().trim().length() > 0) {
			criteria.put(IOMSConstants.CLIENT__LNAME, this._clientLName
					.getText().trim());
		}

		// constructing order date range
		Date shippingDateFrom = new Date(
				this._shippingDateFromTxt.getYear() - 1900,
				this._shippingDateFromTxt.getMonth(), this._shippingDateFromTxt
						.getDay());
		Date shippingDateTo = new Date(
				this._shippingDateToTxt.getYear() - 1900,
				this._shippingDateToTxt.getMonth(), this._shippingDateToTxt
						.getDay());
		DateRange shipping_range = new DateRange(shippingDateFrom,
				shippingDateTo);
		criteria.put(IOMSConstants.PURCHASE_ORDER__EXPECTED_SHIPPING_DATE,
				shipping_range);

		// constructing product & ingredient search criteria
		if (this._prod.getText() != null && this._prod.getText().length() > 0) {
			criteria.put(IOMSConstants.PROD_NAME, this._prod.getText());
		}

		if (this._ingredient.getText() != null
				&& this._ingredient.getText().length() > 0) {
			criteria.put(IOMSConstants.ING_NAME, this._ingredient.getText());
		}

		return criteria;
	}

	@Override
	public void init(IViewSite site) throws PartInitException {

		super.init(site);

		OrdersListView.getOrdersListViewPart(site).addSelectionChangedListener(
				this);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.part.WorkbenchPart#setFocus()
	 */
	@Override
	public void setFocus() {

	}

	@Override
	public void selectionChanged(SelectionChangedEvent event) {
		if (event.getSelection() instanceof IStructuredSelection
				&& ((IStructuredSelection) event.getSelection())
						.getFirstElement() instanceof PurchaseOrder) {

		}
	}

	private GridData createGridDataWithSpan() {
		GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
		gridData.horizontalSpan = 1;
		return gridData;
	}

	private GridData createControlGridData() {
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.grabExcessHorizontalSpace = true;
		gd.horizontalSpan = 2;
		return gd;
	}

	private GridData createLabelGridData() {
		GridData gridData = new GridData();
		gridData.horizontalAlignment = GridData.END;
		gridData.horizontalSpan = 1;
		return gridData;
	}

	public void refreshSearchView() {
		// reload ingredient list
		this._ingredient.setItems(fetchIngredientList());

		// refresh product list
		this._prod.setItems(fetchProductList());
	}

	/**
	 * 
	 * @param site
	 * @return
	 */
	public static OrderDetailsView getOrdersListViewPart(IViewSite site) {
		IViewPart view = site.getPage().findView(OrderDetailsView.ID_VIEW);
		if (view instanceof OrderDetailsView) {
			return ((OrderDetailsView) view);
		}
		return null;
	}
}
